package com.jackstraw.jack_base.datasource.moredatasource.bean;


import com.jackstraw.jack_base.datasource.database.parten.entity.bean.DataBaseFactory;
import com.jackstraw.jack_base.util.CollectionUtil;
import com.jackstraw.jack_base.util.StringUtil;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;


public class HikariDataBaseFactory extends DataBaseFactory<HikariDataBaseEntity> {


    @Override
    protected DataSource dataSource(HikariDataBaseEntity hikariDataBaseEntity) {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setConnectionTimeout(hikariDataBaseEntity.getMaxWait());
        hikariConfig.setIdleTimeout(hikariDataBaseEntity.getMinEvictableIdleTimeMillis());
        hikariConfig.setMaxLifetime(hikariDataBaseEntity.getMaxEvictableIdleTimeMillis());
        hikariConfig.setMaximumPoolSize(hikariDataBaseEntity.getMaxActive());
        hikariConfig.setMinimumIdle(hikariDataBaseEntity.getMinIdle());
        hikariConfig.setPassword(hikariDataBaseEntity.getPassword());
        hikariConfig.setUsername(hikariDataBaseEntity.getUsername());
        hikariConfig.setValidationTimeout(hikariDataBaseEntity.getValidationQueryTimeout());
        hikariConfig.setConnectionTestQuery(CollectionUtil.isEmpty(hikariDataBaseEntity.getConnectionInitSqls())
                ? null : hikariDataBaseEntity.getConnectionInitSqls().get(0));
        if (StringUtil.StringUtilsBylang3.isNotEmpty(hikariDataBaseEntity.getDriverClass())) {
            hikariConfig.setDriverClassName(hikariDataBaseEntity.getDriverClass());
        }
        hikariConfig.setJdbcUrl(hikariDataBaseEntity.getJdbcUrl());
        hikariConfig.setPoolName(hikariDataBaseEntity.getName());

        return new HikariDataSource(hikariConfig);
    }
}
